package com.upc.tp.timeplanning.controller;

import com.upc.tp.timeplanning.entity.ResBody;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.LinkedHashMap;


@RestController
@RequestMapping(value = "/file", method = {RequestMethod.POST, RequestMethod.GET})
public class FileController {

    @PostMapping("/fileUpload")
    public ResBody fileUpload(@RequestBody Object obj) {

        LinkedHashMap<String,String> linkedHashMap=(LinkedHashMap)obj;

        savePicture(linkedHashMap.get("head_photo"),linkedHashMap.get("name"));
        return new ResBody(100,"success",null);
    }

    @GetMapping("/fileDownload")
    public ResBody fileDownload(String name) {

        if (getPicture(name)!=null){
            return new ResBody(100,"success",getPicture(name));
        }
        else{
            return new ResBody(-1,"No Such File",getPicture(name));
        }

    }

    public void savePicture(String head_photo, String name) {
        String separate=System.getProperty("file.separator");

        FileOutputStream output = null;
        File file = new File("ph"+ separate+ name + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        try {
            byte[] bytes1 = Base64.getMimeDecoder().decode(head_photo);
            output = new FileOutputStream(file);

            for (int i = 0; i < bytes1.length; i++) {
                output.write(bytes1[i]);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                output.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getPicture(String name){
        String separate=System.getProperty("file.separator");

        File file=new File("ph"+separate+name+".jpg");

//        System.out.println(file.length());
        byte[] byte1=new byte[(int)file.length()];

        try {
            FileInputStream in=new FileInputStream(file);
            in.read(byte1);

            in.close();
        } catch (IOException e) {
            return null;
        }

        String base64=Base64.getMimeEncoder().encodeToString(byte1);

        return base64;
    }
}
